package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Comment;
import cn.wolfcode.trip.base.domain.StrategyComment;
import cn.wolfcode.trip.base.domain.Tag;
import cn.wolfcode.trip.base.mapper.CommentMapper;
import cn.wolfcode.trip.base.mapper.StrategyCommentMapper;
import cn.wolfcode.trip.base.mapper.TagMapper;
import cn.wolfcode.trip.base.query.StrategyCommentQueryObject;
import cn.wolfcode.trip.base.service.IStrategyCommentService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentMapper strategyCommentMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public PageInfo<StrategyComment> query(StrategyCommentQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyComment> list = strategyCommentMapper.queryForList(qo);
        for (StrategyComment strategyComment : list) {
            //根据点评的id去查询评论数
            int commentNum = commentMapper.selectForNum(strategyComment.getId(), Comment.MODELSTATE_STRATEGYCOMMENT);
            //设置评论数
            strategyComment.setCommentNum(commentNum);
        }
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdate(StrategyComment strategyComment, String[] tags) {
        if (strategyComment.getId()!=null){
            strategyCommentMapper.updateByPrimaryKey(strategyComment);
        }else {
            strategyComment.setCreateTime(new Date());
            strategyComment.setUser(UserContext.getCurrentUser());
            strategyCommentMapper.insert(strategyComment);
            for (String tagName : tags) {
                Tag tag = new Tag();
                tag.setName(tagName);
                tagMapper.insert(tag);
                strategyCommentMapper.insertRelation(strategyComment.getId(),tag.getId());
            }
        }
    }

    @Override
    public StrategyComment selectById(Long id) {
        return strategyCommentMapper.selectByPrimaryKey(id);
    }

}
